package cn.lg.soar.database.handler.type.base;

import cn.lg.soar.common.util.jackson.JacksonUtil;
import cn.lg.soar.common.util.reflect.GenericTypeUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.ArrayType;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

/**
 * 自动json类型数据处理器（类型固定的）
 * 子类只需继承无需实现任何方法即可完成类型处理
 * @author luguoxiang
 * @date 2022-05-20
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public abstract class AutoJsonTypeHandler<T> extends AbstractJsonTypeHandler<T> {

    protected Function<String, T> parser;

    private final static ObjectMapper OBJECT_MAPPER = JacksonUtil.OBJECT_MAPPER;

    public AutoJsonTypeHandler() {
        Type genericType = GenericTypeUtils.getGenericType(this.getClass());
        Class<T> type;
        if (genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            type = (Class<T>) parameterizedType.getRawType();

            if (List.class.isAssignableFrom(type)) {
                Class<?> elementType = (Class<T>) parameterizedType.getActualTypeArguments()[ 0 ];
                CollectionType collectionType = OBJECT_MAPPER
                        .getTypeFactory()
                        .constructCollectionType(ArrayList.class, elementType);
                this.parser = json -> {
                    try {
                        return OBJECT_MAPPER.readValue(json, collectionType);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                };
                return;
            }

            if (Set.class.isAssignableFrom(type)) {
                Class<?> elementType = (Class<T>) parameterizedType.getActualTypeArguments()[ 0 ];
                CollectionType collectionType = OBJECT_MAPPER
                        .getTypeFactory()
                        .constructCollectionType(HashSet.class, elementType);
                this.parser = json -> {
                    try {
                        return OBJECT_MAPPER.readValue(json, collectionType);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                };
                return;
            }
        } else {
            type = (Class<T>) genericType;

            if (type.isArray()) {
                Class<?> elementType = type.getComponentType();
                ArrayType arrayType = OBJECT_MAPPER
                        .getTypeFactory()
                        .constructArrayType(elementType);
                this.parser = json -> {
                    try {
                        return OBJECT_MAPPER.readValue(json, arrayType);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                };
                return;
            }
        }

        this.parser = json -> {
            try {
                return OBJECT_MAPPER.readValue(json, type);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        };

    }

    @Override
    protected T parse(String json) {
        return parser.apply(json);
    }

    @Override
    protected String toJson(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
